﻿/*
 * Author: Thomas Mattsson
 * Alexander Sjösten wrote EmptyTextFields and the event for the Clear button
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Final_Project.SessionData;

namespace Final_Project.CustomerData
{
    /// <summary>
    /// This class represents the window for Customers.
    /// This view lets you interact with customers; add, edit and delete.
    /// </summary>
    public partial class CustomerForm : Form
    {
        // Local variables
        private bool closeForm = true;
        private Customer customer;


        /// <summary>
        /// Default constructor that creates the CustomerForm window.
        /// </summary>
        public CustomerForm()
        {
            InitializeComponent();

            customer = new Customer();

            InitializeGUI();
        }


        /// <summary>
        /// This method initializes the gui components.
        /// </summary>
        private void InitializeGUI()
        {
            lblCustomerID.Text = "- - - -";
            rbtnCashCustomer.Checked = true;
            EmptyTextFields();
            FlipInvoiceFields(false);
            lboxSessions.Items.Clear();
        }


        /// <summary>
        /// Read input from fields and control each of the inputs
        /// by calling Read methods.
        /// </summary>
        /// <returns>True if all checks pass, False otherwise.</returns>
        public bool ReadInput()
        {
            return (ReadFirstName() && ReadLastName() && ReadPhone() && ReadEmail());
        }


        /// <summary>
        /// This method reads the text in the field for first name
        /// and verifies its content before inserting into customer.
        /// </summary>
        private bool ReadFirstName()
        {
            string firstName = txtFirstName.Text.Trim();
            if (string.IsNullOrEmpty(firstName))
            {
                RaiseError("Fel", "Ett fel i fältet för förnamn.");
                return false;
            }
            customer.FirstName = firstName;
            return true;
        }


        /// <summary>
        /// This method reads the text in the field for last name
        /// and verifies its content before inserting into customer.
        /// </summary>
        private bool ReadLastName()
        {
            string lastName = txtLastName.Text.Trim();
            if (string.IsNullOrEmpty(lastName))
            {
                RaiseError("Fel", "Ett fel i fältet för efternamn.");
                return false;
            }
            customer.LastName = lastName;
            return true;
        }


        /// <summary>
        /// This method reads the text in the field for phone number
        /// and verifies its content before inserting into customer.
        /// </summary>
        private bool ReadPhone()
        {
            string phone = txtPhone.Text.Trim();
            if (string.IsNullOrEmpty(phone))
            {
                RaiseError("Fel", "Ett fel i fältet för telefon.");
                return false;
            }
            customer.Phone = phone;
            return true;
        }


        /// <summary>
        /// This method reads the text in the field for email
        /// and verifies its content before inserting into customer.
        /// </summary>
        private bool ReadEmail()
        {
            string toValidate = txtEmail.Text.Trim();
            string email = string.Empty;

            // If email is not set, just set empty and exit
            if (string.IsNullOrEmpty(toValidate))
            {
                customer.Email = string.Empty;
                return true;
            }

            // if not empty, check that email is valid
            if (!InputUtility.GetEmail(toValidate, out email))
            {
                RaiseError("Fel", "Ett fel i fältet för email.");
                return false;
            }
            customer.Email = email;
            return true;
        }


        /// <summary>
        /// This method raises a MessageBox with supplied text and title.
        /// </summary>
        /// <param name="title">Box title</param>
        /// <param name="message">Box message</param>
        private void RaiseError(string title, string message)
        {
            MessageBox.Show(this, message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }


        /// <summary>
        /// This method updates lblCustomerID with a supplied
        /// user ID.
        /// </summary>
        /// <param name="id">The ID to set.</param>
        private void setCustomerIDLabel(int id) {
            lblCustomerID.Text = id.ToString();
        }


        /// <summary>
        /// Property related to customer variable.
        /// </summary>
        public Customer CustomerData
        {
            get { return customer; }
            set
            {
                if (value != null)
                {
                    customer = value;
                    UpdateGUI();
                }
            }
        }


        /// <summary>
        /// This method updates the gui components with new values.
        /// </summary>
        public void UpdateGUI()
        {
            if (customer is InvoiceCustomer)
            {
                rbtnInvoiceCustomer.Checked = true;
                FlipInvoiceFields(true);
                txtCity.Text = ((InvoiceCustomer)customer).City;
                txtStreet.Text = ((InvoiceCustomer)customer).Street;
                txtZip.Text = ((InvoiceCustomer) customer).Zip;
            }
            txtFirstName.Text = customer.FirstName;
            txtLastName.Text = customer.LastName;
            txtPhone.Text = customer.Phone;
            txtEmail.Text = customer.Email;
            lblCustomerID.Text = customer.ID.ToString();
            UpdateSessionList();
        }


        /// <summary>
        /// This method flips the state of the three invoice text fields.
        /// </summary>
        /// <param name="value">True makes fields enabled, False disables fields.</param>
        private void FlipInvoiceFields(bool value)
        {
            txtCity.Enabled = value;
            txtStreet.Enabled = value;
            txtZip.Enabled = value;
        }

        /// <summary>
        /// Method that will empty all the text fields
        /// </summary>
        private void EmptyTextFields()
        {
            txtFirstName.Text = string.Empty;
            txtLastName.Text = string.Empty;
            txtPhone.Text = string.Empty;
            txtEmail.Text = string.Empty;
            txtStreet.Text = string.Empty;
            txtZip.Text = string.Empty;
            txtCity.Text = string.Empty;
        }


        /// <summary>
        /// This method fills the listbox of Sessions with values
        /// stored in customer object.
        /// </summary>
        private void UpdateSessionList()
        {
            lboxSessions.Items.Clear();
            lboxSessions.Items.AddRange(customer.GetSessionsStrings());
        }


        #region Event-handlers


        /// <summary>
        /// Event-handler for the window closing button
        /// </summary>
        /// <param name="sender">Reference to the form</param>
        /// <param name="e">Additional information about the event</param>
        private void CustomerForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (closeForm)
                e.Cancel = false;    // Close the Contact Form
            else
                e.Cancel = true;     // Do not close (user has chosen Cancel)
        }


        /// <summary>
        /// Event-handler for the cash radiobutton
        /// </summary>
        /// <param name="sender">A reference to the radio button</param>
        /// <param name="e">Additional event information.</param>
        private void rbtnCashCustomer_CheckedChanged(object sender, EventArgs e)
        {
            FlipInvoiceFields(false);
        }


        /// <summary>
        /// Event-handler for the invoice radiobutton
        /// </summary>
        /// <param name="sender">A reference to the radio button</param>
        /// <param name="e">Additional event information.</param>
        private void rbtnInvoiceCustomer_CheckedChanged(object sender, EventArgs e)
        {
            FlipInvoiceFields(true);
        }


        /// <summary>
        /// Event-handler for the Save customer button.
        /// </summary>
        /// <param name="sender">A reference to the Add button</param>
        /// <param name="e">Addition event information</param>
        private void btnAddCustomer_Click(object sender, EventArgs e)
        {
            closeForm = false;
            bool result = ReadInput();

            // Invoice customer
            if (rbtnInvoiceCustomer.Checked)
            {
                string street = txtStreet.Text;
                string zip = txtZip.Text;
                string city = txtCity.Text;

                customer = new InvoiceCustomer(customer, street, zip, city);
            }
            else
            {
                customer = new Customer(customer);
            }

            if (result)
                closeForm = true;
        }


        /// <summary>
        /// Event-handler for the Clear button.
        /// </summary>
        /// <param name="sender">A reference to the clear button.</param>
        /// <param name="e">Additional event information.</param>
        private void btnClearInput_Click(object sender, EventArgs e)
        {
            EmptyTextFields();
            rbtnCashCustomer.Checked = true;
            FlipInvoiceFields(false);
        }


        /// <summary>
        /// Event-handler for the close button
        /// </summary>
        /// <param name="sender">A reference to the close button.</param>
        /// <param name="e">Additional event information.</param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show(
                "Stäng utan att spara?",
                "Är du säker?",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question
            );
            
            if (result == DialogResult.Yes)
                closeForm = true;
            else
                closeForm = false;
        }


        /// <summary>
        /// Event-handler for the close button
        /// </summary>
        /// <param name="sender">A reference to the close button.</param>
        /// <param name="e">Additional event information.</param>
        private void btnAddSession_Click(object sender, EventArgs e)
        {
            SessionForm sessForm = new SessionForm();

            // Do we want to save something?
            if (sessForm.ShowDialog() == DialogResult.OK)
            {
                customer.AddSession(sessForm.Session);
                UpdateSessionList();
            }
        }


        /// <summary>
        /// Event-handler for the close button
        /// </summary>
        /// <param name="sender">A reference to the close button.</param>
        /// <param name="e">Additional event information.</param>
        private void btnEditSession_Click(object sender, EventArgs e)
        {
            int index = lboxSessions.SelectedIndex;
            if (index != -1)
            {
                SessionForm frmSession = new SessionForm();
                frmSession.Session = customer.GetTreatmentSession(index);
                frmSession.UpdateGUI();

                if (frmSession.ShowDialog() == DialogResult.OK)
                {
                    UpdateSessionList();
                }
            }
        }


        /// <summary>
        /// Event-handler for the close button
        /// </summary>
        /// <param name="sender">A reference to the close button.</param>
        /// <param name="e">Additional event information.</param>
        private void btnRemoveSession_Click(object sender, EventArgs e)
        {
            int index = lboxSessions.SelectedIndex;
            if (index != -1)
            {
                DialogResult result = MessageBox.Show("Ta bort vald behandling?", "Är du säker?",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                
                if (result == DialogResult.Yes)
                {
                    customer.RemoveSession(index);
                    UpdateSessionList();
                }
            }
        }

        #endregion

    }
}
